<?php

require_once 'Pipes/Exception.php';
require_once 'PipesCore/Helpers/Grid/AttributeParser.php';
require_once 'PipesImpl/Visitor.php';

class Pipes_Helpers_Grid_ElementParser implements PipesImpl_Visitor
{
	private $_variables = array();
	public function __construct(array $variables) {
		$this->_variables = $variables;
	}

	public function visit(PipesImpl_Visitable $visitable) {
		if (!$visitable instanceof Pipes_Xml_Element) {
			throw new Pipes_Exception('ERR_INVALID_VISITOR');
		}
		
		// pull variables into current scope
		extract($this->_variables);
		
		foreach ($visitable->childNodes as $xmlElement) {
			
			// perform visit on all children
			if ($xmlElement->hasChildNodes()) {
				$xmlElement->accept($this);
			}
			
			// replace out attributes
			if ($xmlElement->hasAttributes()) {
				$xmlElement->accept(
					new Pipes_Helpers_Grid_AttributeParser($this->_variables)
				);
			}
			
			if ($xmlElement->nodeName != "#text") {
				// we only want to perform changes on #text elements
				continue;
			}
			
			// find matching replacement strings
			preg_match_all(
				'/\{\$([^-]+)->([^\}]+)\}/', 
				$xmlElement->nodeValue,
				$matches);
			
			// handle actual replacement
			foreach ($matches[0] as $matchKey => $match) {
				$search = $match;
				
				$replaceObject = $matches[1][$matchKey];
				$replaceProp = $matches[2][$matchKey];
				$replace = $$replaceObject->$replaceProp;
				$xmlElement->nodeValue = str_replace($search, $replace, $xmlElement->nodeValue);
			}
		}
	}
}
